import React, { useEffect, useState } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  useTheme,
  useMediaQuery,
  Alert,
  Snackbar,
  Tabs,
  Tab,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
} from '@mui/material';
import {
  Add as AddIcon,
  Delete as DeleteIcon,
  Person as PersonIcon,
  Edit as EditIcon,
  Close as CloseIcon,
} from '@mui/icons-material';
import apiClient from '../services/apiService';
import Dashboard from './Dashboard';
import DeviceManagement from './DeviceManagement';
import UserProfileEdit from '../components/UserProfileEdit';
import { User } from '../types/auth';

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [openDialog, setOpenDialog] = useState(false);
  const [openProfileDialog, setOpenProfileDialog] = useState(false);
  const [activeTab, setActiveTab] = useState(0);
  const [newUser, setNewUser] = useState({
    username: '',
    email: '',
    password: '',
    role: 'user',
  });
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [openEditDialog, setOpenEditDialog] = useState(false);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const fetchUsers = async () => {
    try {
      const response = await apiClient.get('/auth/users');
      setUsers(response.data);
    } catch (error: any) {
      setError('获取用户列表失败：' + (error.response?.data?.message || error.message));
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleCreateUser = async () => {
    try {
      await apiClient.post('/auth/users', {
        username: newUser.username,
        email: newUser.email,
        password: newUser.password,
        role: newUser.role
      });
      setSuccess('用户创建成功');
      setOpenDialog(false);
      setNewUser({ username: '', email: '', password: '', role: 'user' });
      fetchUsers();
    } catch (error: any) {
      setError('创建用户失败：' + (error.response?.data?.message || error.message));
    }
  };

  const handleDeleteUser = async (userId: string) => {
    if (!userId) return;
    if (!window.confirm('确定要删除该用户吗？此操作不可恢复。')) {
      return;
    }
    try {
      await apiClient.delete(`/auth/users/${userId}`);
      setSuccess('用户删除成功');
      fetchUsers();
    } catch (error: any) {
      setError('删除用户失败：' + (error.response?.data?.message || error.message));
    }
  };

  const handleViewUserProfile = (user: User) => {
    setSelectedUser(user);
    setOpenProfileDialog(true);
    setActiveTab(0);
  };

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setActiveTab(newValue);
  };

  const handleEditUser = (user: User) => {
    setSelectedUser(user);
    setOpenEditDialog(true);
  };

  return (
    <Box sx={{ p: { xs: 2, sm: 3 } }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant={isMobile ? "h5" : "h4"} gutterBottom>
          用户管理
        </Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => setOpenDialog(true)}
        >
          创建用户
        </Button>
      </Box>

      <TableContainer component={Paper} elevation={0}>
        <Table size={isMobile ? "small" : "medium"}>
          <TableHead>
            <TableRow>
              <TableCell>用户名</TableCell>
              <TableCell>邮箱</TableCell>
              {!isMobile && <TableCell>角色</TableCell>}
              {!isMobile && <TableCell>注册时间</TableCell>}
              <TableCell align="right">操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {users.map((user) => (
              <TableRow key={user._id || user.id}>
                <TableCell>{user.username}</TableCell>
                <TableCell>{user.email}</TableCell>
                {!isMobile && <TableCell>{user.role === 'admin' ? '管理员' : '普通用户'}</TableCell>}
                {!isMobile && <TableCell>{new Date(user.createdAt).toLocaleString()}</TableCell>}
                <TableCell align="right">
                  <IconButton
                    color="primary"
                    onClick={() => handleViewUserProfile(user)}
                    size={isMobile ? "small" : "medium"}
                    title="查看用户主页"
                  >
                    <PersonIcon />
                  </IconButton>
                  <IconButton
                    color="primary"
                    onClick={() => handleEditUser(user)}
                    size={isMobile ? "small" : "medium"}
                    title="编辑用户"
                  >
                    <EditIcon />
                  </IconButton>
                  <IconButton
                    color="error"
                    onClick={() => {
                      const userId = user._id || user.id;
                      if (userId) {
                        handleDeleteUser(userId);
                      }
                    }}
                    size={isMobile ? "small" : "medium"}
                    title="删除用户"
                  >
                    <DeleteIcon />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 创建用户对话框 */}
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="sm" fullWidth>
        <DialogTitle>创建新用户</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 2 }}>
            <TextField
              label="用户名"
              value={newUser.username}
              onChange={(e) => setNewUser({ ...newUser, username: e.target.value })}
              fullWidth
            />
            <TextField
              label="邮箱"
              type="email"
              value={newUser.email}
              onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
              fullWidth
            />
            <TextField
              label="密码"
              type="password"
              value={newUser.password}
              onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
              fullWidth
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>取消</Button>
          <Button onClick={handleCreateUser} variant="contained">
            创建
          </Button>
        </DialogActions>
      </Dialog>

      {/* 用户主页弹窗 */}
      <Dialog 
        open={openProfileDialog} 
        onClose={() => setOpenProfileDialog(false)} 
        maxWidth="xl" 
        fullWidth
        PaperProps={{
          sx: {
            height: isMobile ? '100vh' : '90vh',
            maxHeight: isMobile ? '100vh' : '90vh',
            m: isMobile ? 0 : 2,
            borderRadius: isMobile ? 0 : 1,
          }
        }}
      >
        <DialogTitle sx={{ 
          p: isMobile ? 1 : 2,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <Typography variant={isMobile ? "h6" : "h5"}>
            {selectedUser?.username} 的主页
          </Typography>
          <IconButton
            onClick={() => setOpenProfileDialog(false)}
            size={isMobile ? "small" : "medium"}
            sx={{ ml: 1 }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent sx={{ p: isMobile ? 1 : 3, height: 'calc(100% - 64px)' }}>
          <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
            <Tabs value={activeTab} onChange={handleTabChange} variant={isMobile ? "fullWidth" : "standard"}>
              <Tab label="仪表盘" />
              <Tab label="设备管理" />
            </Tabs>
          </Box>
          <Box sx={{ p: isMobile ? 1 : 3, height: 'calc(100% - 48px)', overflow: 'auto' }}>
            {activeTab === 0 && selectedUser && (
              <Dashboard userId={selectedUser.id} />
            )}
            {activeTab === 1 && selectedUser && (
              <DeviceManagement userId={selectedUser.id} />
            )}
          </Box>
        </DialogContent>
      </Dialog>

      {/* 编辑用户对话框 */}
      {selectedUser && (
        <UserProfileEdit
          user={selectedUser}
          open={openEditDialog}
          onClose={() => setOpenEditDialog(false)}
          onSuccess={fetchUsers}
          isAdmin={true}
        />
      )}

      {/* 提示消息 */}
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={() => setError(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="error" onClose={() => setError(null)}>
          {error}
        </Alert>
      </Snackbar>

      <Snackbar
        open={!!success}
        autoHideDuration={6000}
        onClose={() => setSuccess(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="success" onClose={() => setSuccess(null)}>
          {success}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default UserManagement; 